package cn.cslg.news.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cslg.news.db.JndiBean;
import cn.cslg.news.entity.Member;
import cn.cslg.news.pager.DataPageServlet;
import cn.cslg.news.pager.Page;


@WebServlet("/admin/paginated_userlist")
public class PaginatedUserListServlet extends DataPageServlet {
	private static final long serialVersionUID = -8605388093529720502L;

	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        url = getServletContext().getAttribute("ContextPath") + "admin/paginated_userlist";
        view = "/WEB-INF/jsp/user.jsp";
        pageSize = 20;
        super.doGet(req, resp);
    }

    @Override
    public int getTotalRows() throws ServletException {
        try (Connection conn = JndiBean.getConnection()) {
            String sql = "select count(uid) as tc  from member";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            rs.next();
            return rs.getInt("tc");
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    @Override
    public List<Object> getPageDataRows(Page page) throws ServletException {
        try (Connection conn = JndiBean.getConnection()) {
            String sql = "select uid,username,password,truename,email,enabled,activated  from member limit %d,%d";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(String.format(sql, page.getBeginIndex(), page.getPageSize()));
            List<Object> arr = new ArrayList<Object>();
            while (rs.next()) {
            	Member u=new Member();
            	u.setUid(rs.getInt("uid"));
				u.setTruename(rs.getString("truename"));
				u.setUsername(rs.getString("username"));
				u.setPassword(rs.getString("password"));
				u.setEmail(rs.getString("email"));
				u.setActivated(rs.getInt("activated"));
				u.setEnabled(rs.getInt("enabled"));
                arr.add(u);
            }
            return arr;
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}

